#include "../source/common/net.hpp"
#include "../source/common/dispatcher.hpp"
#include "../source/server/rpc_router.hpp"

#include <memory>
#include <functional>

void ADD(const Json::Value &params, Json::Value &result)
{
    int num1 = params["num1"].asInt();
    int num2 = params["num2"].asInt();
    result = num1 + num2;
}

// server->dispatcher->router->method
int main()
{
    JsonMuduoRPC::server::RPCRouter::ptr rpc_router = std::make_shared<JsonMuduoRPC::server::RPCRouter>();

    //0. 构建服务描述
    JsonMuduoRPC::server::ServiceDescribeFactory service_factory;
    service_factory.setParamsDescribe("num1", JsonMuduoRPC::server::VType::INTEGRAL);
    service_factory.setParamsDescribe("num2", JsonMuduoRPC::server::VType::INTEGRAL);
    service_factory.setResultType(JsonMuduoRPC::server::VType::INTEGRAL);
    service_factory.setServiceCallBack(ADD);
    service_factory.setServiceName("ADD");

    // 1. 将ADD服务注册到RPCRouter中
    rpc_router->registerService(service_factory.bulid());

    // 2. 将RPCRouter中的处理消息模块设置到dispatcher中
    auto dispatcher = std::make_shared<JsonMuduoRPC::Dispatcher>();

    auto router_on_message = std::bind(&JsonMuduoRPC::server::RPCRouter::onRpcRequest, rpc_router.get(),
                                       std::placeholders::_1, std::placeholders::_2);

    dispatcher->registerHandler<JsonMuduoRPC::RPCRequest>(JsonMuduoRPC::MType::REQ_RPC, router_on_message); // 注册映射

    // 3. 将dispatcher中的处理消息模块设置到server中
    auto server = JsonMuduoRPC::ServerFactory::create(8080);
    server->setMessageCallBack(std::bind(&JsonMuduoRPC::Dispatcher::onMessage, dispatcher.get(),
                                         std::placeholders::_1, std::placeholders::_2));
    server->start();

    return 0;
}